/*
 * EditarAgenda.java
 *
 * Created on 30/04/2011, 11:11:32
 */

package pbf.internalframe;

import calendario.InterFaceCalendario;
import java.util.ArrayList;
import javax.swing.ButtonGroup;
import javax.swing.table.DefaultTableModel;
import org.hibernate.Session;
import pbf.conf.hibernate.HibernateUtil;
import pbf.conf.hibernate.entidades.Agendamento;
import pbf.util.DataHora;
import pbf.util.Mensagem;

/**
 *
 * @author Ricardo
 */
public class EditarAgenda extends javax.swing.JInternalFrame {

    private ButtonGroup grupoBotao = new ButtonGroup();
    private Session sessao = null;

    public EditarAgenda() {
        initComponents();
        grupoBotao.add(radioNome);
        grupoBotao.add(radioData);
        agendamentoDtAtendimento.setText(DataHora.getDataPresente());
        desabilitaBusca();
    }

    private void desabilitaBusca(){
        agendamentoDtAtendimento.setVisible(false);
        botaoCalendario.setVisible(false);
        familiaNome.setVisible(false);
        familiaNome.setText("");
        DefaultTableModel model = (DefaultTableModel) tabela.getModel();
        model.setNumRows(0);
    }

    private void ativaBusca()
    {
        desabilitaBusca();

        if(radioNome.isSelected())
        {
            familiaNome.setVisible(true);
        }
        else
        {
            botaoCalendario.setVisible(true);
            agendamentoDtAtendimento.setVisible(true);
        }
        
        botaoBuscar.setEnabled(true);
    }


    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        agendamentoDtAtendimento = new javax.swing.JLabel();
        botaoCalendario = new javax.swing.JLabel();
        jScrollPane1 = new javax.swing.JScrollPane();
        tabela = new javax.swing.JTable();
        jButton1 = new javax.swing.JButton();
        jSeparator1 = new javax.swing.JSeparator();
        radioNome = new javax.swing.JRadioButton();
        radioData = new javax.swing.JRadioButton();
        jLabel1 = new javax.swing.JLabel();
        familiaNome = new javax.swing.JTextField();
        jButton2 = new javax.swing.JButton();
        jButton3 = new javax.swing.JButton();
        botaoBuscar = new javax.swing.JButton();
        jLabel2 = new javax.swing.JLabel();

        setClosable(true);
        setDefaultCloseOperation(javax.swing.WindowConstants.HIDE_ON_CLOSE);
        setResizable(true);
        getContentPane().setLayout(null);

        agendamentoDtAtendimento.setFont(new java.awt.Font("Tahoma", 0, 16));
        agendamentoDtAtendimento.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT);
        agendamentoDtAtendimento.setText("12/05/2011");
        getContentPane().add(agendamentoDtAtendimento);
        agendamentoDtAtendimento.setBounds(60, 110, 90, 20);

        botaoCalendario.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
        botaoCalendario.setIcon(new javax.swing.ImageIcon(getClass().getResource("/pbf/imagens/calendar-month.png"))); // NOI18N
        botaoCalendario.setVerticalAlignment(javax.swing.SwingConstants.BOTTOM);
        botaoCalendario.setCursor(new java.awt.Cursor(java.awt.Cursor.HAND_CURSOR));
        botaoCalendario.setHorizontalTextPosition(javax.swing.SwingConstants.LEFT);
        botaoCalendario.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                botaoCalendarioMouseClicked(evt);
            }
            public void mouseEntered(java.awt.event.MouseEvent evt) {
                botaoCalendarioMouseEntered(evt);
            }
            public void mouseExited(java.awt.event.MouseEvent evt) {
                botaoCalendarioMouseExited(evt);
            }
        });
        getContentPane().add(botaoCalendario);
        botaoCalendario.setBounds(20, 100, 30, 30);

        tabela.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
        tabela.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {"1985", "30/04/2011", "Ricardo Tavares Antunes de Oliveira"},
                {null, null, null},
                {null, null, null},
                {null, null, null}
            },
            new String [] {
                "ID", "Data", "Nome do Responsável"
            }
        ) {
            boolean[] canEdit = new boolean [] {
                false, false, false
            };

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        tabela.getTableHeader().setReorderingAllowed(false);
        jScrollPane1.setViewportView(tabela);
        tabela.getColumnModel().getColumn(0).setPreferredWidth(50);
        tabela.getColumnModel().getColumn(0).setMaxWidth(50);
        tabela.getColumnModel().getColumn(1).setPreferredWidth(100);
        tabela.getColumnModel().getColumn(1).setMaxWidth(100);

        getContentPane().add(jScrollPane1);
        jScrollPane1.setBounds(20, 170, 540, 160);

        jButton1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/pbf/imagens/cross-circle.png"))); // NOI18N
        jButton1.setText("Cancelar");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });
        getContentPane().add(jButton1);
        jButton1.setBounds(450, 360, 110, 25);
        getContentPane().add(jSeparator1);
        jSeparator1.setBounds(0, 350, 570, 10);

        radioNome.setText("Nome do Responsável");
        radioNome.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                radioNomeActionPerformed(evt);
            }
        });
        getContentPane().add(radioNome);
        radioNome.setBounds(20, 40, 180, 23);

        radioData.setText("Data do Agendamento");
        radioData.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                radioDataActionPerformed(evt);
            }
        });
        getContentPane().add(radioData);
        radioData.setBounds(200, 40, 150, 23);

        jLabel1.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N
        jLabel1.setBorder(javax.swing.BorderFactory.createTitledBorder(null, "Selecione o Tipo de Busca", javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.DEFAULT_POSITION, new java.awt.Font("Tahoma", 1, 14))); // NOI18N
        getContentPane().add(jLabel1);
        jLabel1.setBounds(10, 20, 550, 60);

        familiaNome.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
        getContentPane().add(familiaNome);
        familiaNome.setBounds(20, 110, 530, 23);

        jButton2.setIcon(new javax.swing.ImageIcon(getClass().getResource("/pbf/imagens/date_edit.png"))); // NOI18N
        jButton2.setText("Editar");
        jButton2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton2ActionPerformed(evt);
            }
        });
        getContentPane().add(jButton2);
        jButton2.setBounds(330, 360, 110, 25);

        jButton3.setIcon(new javax.swing.ImageIcon(getClass().getResource("/pbf/imagens/date_delete.png"))); // NOI18N
        jButton3.setText("Apagar");
        jButton3.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton3ActionPerformed(evt);
            }
        });
        getContentPane().add(jButton3);
        jButton3.setBounds(210, 360, 110, 25);

        botaoBuscar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/pbf/imagens/date_magnify.png"))); // NOI18N
        botaoBuscar.setText("Buscar");
        botaoBuscar.setEnabled(false);
        botaoBuscar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                botaoBuscarActionPerformed(evt);
            }
        });
        getContentPane().add(botaoBuscar);
        botaoBuscar.setBounds(430, 140, 130, 25);

        jLabel2.setBorder(javax.swing.BorderFactory.createTitledBorder(null, "Informe", javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.DEFAULT_POSITION, new java.awt.Font("Tahoma", 1, 14))); // NOI18N
        getContentPane().add(jLabel2);
        jLabel2.setBounds(10, 80, 550, 60);

        java.awt.Dimension screenSize = java.awt.Toolkit.getDefaultToolkit().getScreenSize();
        setBounds((screenSize.width-588)/2, (screenSize.height-436)/2, 588, 436);
    }// </editor-fold>//GEN-END:initComponents

    private void botaoCalendarioMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_botaoCalendarioMouseClicked
        InterFaceCalendario calendario = new InterFaceCalendario(null, true);
        calendario.setVisible(true);
        agendamentoDtAtendimento.setText(calendario.getData());
}//GEN-LAST:event_botaoCalendarioMouseClicked

    private void botaoCalendarioMouseEntered(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_botaoCalendarioMouseEntered
        botaoCalendario.setBorder(javax.swing.BorderFactory.createBevelBorder(javax.swing.border.BevelBorder.RAISED));
}//GEN-LAST:event_botaoCalendarioMouseEntered

    private void botaoCalendarioMouseExited(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_botaoCalendarioMouseExited
        botaoCalendario.setBorder(null);
}//GEN-LAST:event_botaoCalendarioMouseExited

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
        setVisible(false);
}//GEN-LAST:event_jButton1ActionPerformed

    private void radioNomeActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_radioNomeActionPerformed
    ativaBusca();
    }//GEN-LAST:event_radioNomeActionPerformed

    private void radioDataActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_radioDataActionPerformed
    ativaBusca();
    }//GEN-LAST:event_radioDataActionPerformed

    private void botaoBuscarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_botaoBuscarActionPerformed
        sessao = HibernateUtil.openSession();
        sessao.beginTransaction();
        DefaultTableModel model = (DefaultTableModel) tabela.getModel();
        model.setNumRows(0);
        ArrayList<Agendamento> listaAgendamentos;
        Object[] objetos = new Object[3];

        if (radioData.isSelected()) {
            listaAgendamentos = (ArrayList<Agendamento>) sessao.createQuery("From pbf.conf.hibernate.entidades.Agendamento WHERE AGENDAMENTO_ATIVO='S' AND (AGENDAMENTO_DT_ATENDIMENTO BETWEEN '" + DataHora.converteStringData(agendamentoDtAtendimento.getText()) + " 00:00:00 ' AND '" + DataHora.converteStringData(agendamentoDtAtendimento.getText()) + " 23:59:59') ORDER BY AGENDAMENTO_AT_PREFERENCIAL ASC").list();

            for (Agendamento f : listaAgendamentos) {
                objetos[0] = f.getAgendamentoId();
                objetos[1] = DataHora.getData(f.getAgendamentoDtAtendimento());
                objetos[2] = f.getFamilia().getFamiliaNome();

                model.addRow(objetos);
            }
        } else {
            listaAgendamentos = (ArrayList<Agendamento>) sessao.createSQLQuery("SELECT * FROM agendamento,familia WHERE FAMILIA_ID=AGENDAMENTO_FK_FAMILIA AND AGENDAMENTO_ATIVO='S' AND (FAMILIA_NOME LIKE '" + familiaNome.getText().toUpperCase() + "%')").addEntity(Agendamento.class).list();

            for (Agendamento f : listaAgendamentos) {
                objetos[0] = f.getAgendamentoId();
                objetos[1] = DataHora.getData(f.getAgendamentoDtAtendimento());
                objetos[2] = f.getFamilia().getFamiliaNome();

                model.addRow(objetos);
            }
        }
        sessao.getTransaction().commit();
        sessao.close();
    }//GEN-LAST:event_botaoBuscarActionPerformed

    private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton3ActionPerformed
        sessao = HibernateUtil.openSession();
        //Inicia uma Transação
        sessao.getTransaction().begin();
        try {
            //Pega a linha que esta seleconada
            int linha = tabela.getSelectedRow();

            Agendamento agendamento = (Agendamento) sessao.createQuery("From pbf.conf.hibernate.entidades.Agendamento where AGENDAMENTO_ID='" + Integer.parseInt(tabela.getValueAt(linha, 0).toString()) + "' ").uniqueResult();

            if (Mensagem.mensageiroDialog("Deseja remover este agendamento?", "Remover", Mensagem.SIM_NAO_OPCAO, getClass().getResource("/pbf/imagens/deletando.png")) == Mensagem.SIM_OPCAO) {
                if (Mensagem.mensageiroDialog("Tem certeza que deseja remove o agendamento do(a) Senhor(a):" + agendamento.getFamilia().getFamiliaNome() + "\nAgendado para: " + DataHora.getData(agendamento.getAgendamentoDtAtendimento()), "Remover", Mensagem.SIM_NAO_OPCAO, getClass().getResource("/pbf/imagens/deletando.png")) == Mensagem.SIM_OPCAO) {
                    agendamento.setAgendamentoAtivo("N");
                    sessao.update(agendamento);
                    DefaultTableModel model = (DefaultTableModel) tabela.getModel();
                    model.removeRow(linha);
                }
            }

        } catch (Exception e) {
            Mensagem.mensagerio("Selecione um registro da Tabela para Continua", "Mensagem", Mensagem.ATENCAO_MENSAGEM);
        }
        sessao.getTransaction().commit();
        sessao.close();
    }//GEN-LAST:event_jButton3ActionPerformed

    private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed
        sessao = HibernateUtil.openSession();
        //Inicia uma Transação
        sessao.getTransaction().begin();
        try {
            //Pega a linha que esta seleconada
            int linha = tabela.getSelectedRow();
            Agendamento agendamento = (Agendamento) sessao.createQuery("From pbf.conf.hibernate.entidades.Agendamento where AGENDAMENTO_ID='" + Integer.parseInt(tabela.getValueAt(linha, 0).toString()) + "' ").uniqueResult();

            pbf.dialog.AlterarAgendamento AlterarAgendamento = new pbf.dialog.AlterarAgendamento(null, true);
            AlterarAgendamento.setAgendamento(agendamento);
            AlterarAgendamento.setVisible(true);
            DefaultTableModel model = (DefaultTableModel) tabela.getModel();
            model.setNumRows(0);

        } catch (Exception e) {
            Mensagem.mensagerio("Selecione um registro da Tabela para Continua ", "Mensagem", Mensagem.ATENCAO_MENSAGEM);
        }
        sessao.getTransaction().commit();
        sessao.close();
    }//GEN-LAST:event_jButton2ActionPerformed


    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JLabel agendamentoDtAtendimento;
    private javax.swing.JButton botaoBuscar;
    private javax.swing.JLabel botaoCalendario;
    private javax.swing.JTextField familiaNome;
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton2;
    private javax.swing.JButton jButton3;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JSeparator jSeparator1;
    private javax.swing.JRadioButton radioData;
    private javax.swing.JRadioButton radioNome;
    public static javax.swing.JTable tabela;
    // End of variables declaration//GEN-END:variables

}
